package com.xinzhitong.www.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xinzhitong.www.enumeration.CollectionType;
import com.xinzhitong.www.exception.BusyException;
import com.xinzhitong.www.exception.collection.CollectionEmptyException;
import com.xinzhitong.www.exception.collection.CollectionExistException;
import com.xinzhitong.www.exception.collection.CollectionNotExistException;
import com.xinzhitong.www.mapper.CollectionMapper;
import com.xinzhitong.www.pojo.User;
import com.xinzhitong.www.service.CollectionService;
import com.xinzhitong.www.utils.FileHelper;
import com.xinzhitong.www.utils.MyPageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 收藏服务实现类
 *
 * @author 徐鑫
 */
@Service
@Transactional
public class CollectionServiceImpl implements CollectionService {

    @Resource
    CollectionMapper collectionMapper;

    private static Map<String, String> typeDictionary = new HashMap<>();

    static {
        typeDictionary.put(CollectionType.COMPANY.toString(), "公司");
        typeDictionary.put(CollectionType.CONSIGN.toString(), "委培");
        typeDictionary.put(CollectionType.COURSE.toString(), "课程");
        typeDictionary.put(CollectionType.NEWS.toString(), "新闻");
        typeDictionary.put(CollectionType.POST.toString(), "岗位");
    }

    @Override
    public MyPageInfo getCollections(CollectionType collectionType, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        //视图名 = 收藏类型 + "_collections"
        String table = collectionType.toString().toLowerCase() + "_collections";
        List<Map<String, Object>> res = collectionMapper.selectCollections(getUsername(), table);
        if (res.size() == 0)
            throw new CollectionEmptyException();
        //补全url
        for (Map<String, Object> one : res)
            one.put("picture", FileHelper.fileURL + one.get("picture"));
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(res);
        return new MyPageInfo(pageInfo);
    }

    @Override
    public void addACollection(Integer id, CollectionType collectionType) {
        if (targetNotExist(id, collectionType))
            throw new CollectionNotExistException();
        String username = getUsername();
        String idField = collectionType.toString().toLowerCase() + "_id";
        //表名 = "user_collect_" + 收藏类型
        String table = "user_collect_" + collectionType.toString().toLowerCase();
        try {
            if (collectionMapper.insertCollection(table, idField, username, id) == 0)
                throw new BusyException();
        } catch (DuplicateKeyException e) {
            e.printStackTrace();
            throw new CollectionExistException(typeDictionary.get(collectionType.toString()));
        }
    }

    @Override
    public void removeTheCollectionOf(Integer[] ids, CollectionType[] collectionType) {
        //初始化用户名
        String username = getUsername();

        //初始化每个类型的id的列表
        Map<String, List<Integer>> idsMap = new HashMap<>();
        for (CollectionType tmp : CollectionType.values()) {
            if (!idsMap.containsKey(tmp.toString()))
                idsMap.put(tmp.toString(), new ArrayList<>());
        }

        //将id们装配入对应的列表
        for (int i = 0; i < ids.length; i++)
            idsMap.get(collectionType[i].toString()).add(ids[i]);

        //数据库操作
        for (CollectionType tmp : CollectionType.values()) {
            //初始化范围参数
            List<Integer> tmpIds = idsMap.get(tmp.toString());
            StringBuilder range = new StringBuilder("(");
            int size = tmpIds.size();
            if (size == 0)
                continue;
            for (int i = 0; i < size; i++) {
                if (i == 0)
                    range.append(ids[i]);
                else
                    range.append(", ").append(ids[i]);
            }
            range.append(")");

            //表名 = "user_collect_" + 收藏类型
            String table = "user_collect_" + tmp.toString().toLowerCase();
            //id字段名 = 收藏类型 + "_id"
            String idField = tmp.toString().toLowerCase() + "_id";

            Integer res = collectionMapper.deleteCollections(table, idField, username, range.toString());
            if (res == 0)
                throw new BusyException();
        }
    }

    /**
     * 判断收藏目标不存在
     *
     * @param id         收藏目标id
     * @param targetType 收藏类型
     * @return 是否不存在
     */
    private boolean targetNotExist(Integer id, CollectionType targetType) {
        //表名 = 目标类型
        String table = targetType.toString().toLowerCase();
        return collectionMapper.selectCollection(table, id) == null;
    }

    /**
     * 获取用户的用户名
     *
     * @return 用户名
     */
    private String getUsername() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        return user.getUsername();
    }

}
